package utl.mofen.dbHandler;

import org.apache.log4j.Logger;

import utl.mofen.dbOperator.ExecuteScript;
import utl.mofen.utils.GsonUtil;


import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

public class ExecuteScriptHandler extends DBBaseHandler {
	private static final Logger logger = Logger.getLogger(ExecuteScriptHandler.class);
    ExecuteScript executer = new ExecuteScript();

	private void execute(JsonElement config) throws Exception
	{
		if (config == null) return;
		if (config.isJsonNull()) return;		
		JsonObject script = config.getAsJsonObject();

		executer.clear();
		executer.setConfig(script);
		executer.executeParseSQL();
		if (isTrace)
		{
			writeTraceSQL(executer.getParsedSQL());				
		}
		
		int r= executer.execute(true);
		
		logger.info("成功执行了一个SQL,影响行数:" +r + "配置:" + GsonUtil.json2String(config));
	}
	
	public void doAction() throws Exception {	
		
		JsonObject json = config;

		executer.setDBOpera(this.dbOpera);
		executer.setSQLParser(this.sqlParser);	
			
		execute(json.get("script"));		
		if (json.has("list"))
		{
			JsonArray upList = json.get("list").getAsJsonArray();
			for (int i = 0; i < upList.getAsJsonArray().size(); i++) 
			{
				execute(upList.get(i));					
			}
		}

	}
}
